//
//  NetworkTools.swift
//  AFNetworking Swift自定义
//
//  Created by Tiffany宝 on 16/4/18.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

//AFNetworking是OC的,所以在swift中要桥接
import UIKit
import AFNetworking

enum RequestMethod: String{
    
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    //单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    //起别名
    typealias RequestCallBack = (responseObject:AnyObject?,error:NSError?) -> Void
    
    func request(method: RequestMethod = .GET, urlString: String, parameters: AnyObject?, finished: RequestCallBack){
        
        // 定义一个请求成功之后要执行的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            // 请求成功后的回调
            finished(responseObject: responseObject, error: nil)
        }
        
        // 定义一个请求失败之后要执行的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            //请求失败后的回调
            finished(responseObject: nil, error: error)
        }
        
        if method == .GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
    //上传图片
    func postPicture(urlString: String,datas:[String : NSData] , parameters: AnyObject?, finished: RequestCallBack){
        
        self.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            //拼装要上传的二进制数据
            /**
            - 1. 要上传的二进制数据
            - 2. 该二进制数组对应的接口里面的名字
            - 3. 传到后台之后的文字名字。一般都乱写，因为后台基本不会使用你写的名字
            - 4. mimeType: 告诉后台我们传上去的二进行数据具体是什么类型的
            - image/jpeg
            - 大类型/小类型
            - 如果不想让后台知道：application/octet-stream
            */
            for (key,value) in datas{
                formData.appendPartWithFileData(value, name: key, fileName: "bbaj.png", mimeType: "application/octet-stream")
            }
            }, progress: nil, success: { (_, responseObject) -> Void in
                finished(responseObject: responseObject, error: nil)
            }) { (_, error) -> Void in
                finished(responseObject: nil, error: error)
        }
    }
}


